package com.framework.service.core.service.impl;

import com.alibaba.fastjson.JSON;
import com.framework.common.Enums.FrameworkErrorCodeEnum;
import com.framework.common.Enums.UserStatusEnum;
import com.framework.common.Enums.UserTypeEnum;
import com.framework.common.constant.Constants;
import com.framework.common.exception.BusinessException;
import com.framework.common.util.FastDFSClient;
import com.framework.common.util.RedisUtils;
import com.framework.service.core.dao.mapper.CustomInfoMapper;
import com.framework.service.core.dao.mapper.ThirdUserInfoMapper;
import com.framework.service.core.dao.mapper.old.UserMapper;
import com.framework.service.core.dao.mapper.old.UserRoleMapper;
import com.framework.service.core.dao.model.CustomInfo;
import com.framework.service.core.dao.model.ThirdUserInfo;
import com.framework.service.core.dao.model.old.User;
import com.framework.service.core.service.ICityService;
import com.framework.service.core.service.IFileService;
import com.framework.service.core.service.IThirdUserInfoService;
import com.framework.service.core.service.IWeixinService;
import com.framework.core.api.request.CityQueryReq;
import com.framework.core.api.request.ThirdUserInfoReq;
import com.framework.core.api.response.CityQueryRes;
import com.framework.core.api.response.ThirdUserInfoQueryRes;
import com.framework.core.api.response.ThirdUserInfoRes;
import com.framework.core.api.response.UploadRes;
import com.framework.service.core.dao.mapper.CustomInfoMapper;
import com.framework.service.core.dao.mapper.ThirdUserInfoMapper;
import com.framework.service.core.dao.mapper.old.UserMapper;
import com.framework.service.core.dao.mapper.old.UserRoleMapper;
import com.framework.service.core.dao.model.CustomInfo;
import com.framework.service.core.dao.model.ThirdUserInfo;
import com.framework.service.core.dao.model.old.User;
import com.framework.service.core.service.ICityService;
import com.framework.service.core.service.IFileService;
import com.framework.service.core.service.IThirdUserInfoService;
import com.framework.service.core.service.IWeixinService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author zhoubb
 * @version V1.0
 * @Date 2020/4/13 23:48
 * @since JDK 1.8
 */
@Service
@Slf4j
public class ThirdUserInfoServiceImpl implements IThirdUserInfoService {

    @Autowired
    private ThirdUserInfoMapper thirdUserInfoMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private CustomInfoMapper customInfoMapper;

    @Autowired
    private IWeixinService weixinService;

    @Autowired
    private ICityService cityService;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private FastDFSClient fastDFSClient;

    @Autowired
    private IFileService fileService;

    @PostConstruct
    public void postConstruct() {
        thirdUserInfoMapper.selectByPrimaryKey(1);
        userMapper.selectById(1);
    }

    @Override
    public ThirdUserInfoRes insertThirdUserInfo(ThirdUserInfoReq thirdUserInfoReq) {
        ThirdUserInfoRes thirdUserInfoRes = new ThirdUserInfoRes();
        if (null == thirdUserInfoReq) {
            log.warn("第三方用户新增操作-请求参数为空");
            thirdUserInfoRes.setCode(FrameworkErrorCodeEnum.PAPAM_IS_NULL.getCode());
            thirdUserInfoRes.setMsg(FrameworkErrorCodeEnum.PAPAM_IS_NULL.getMsg());
            return thirdUserInfoRes;
        }
        log.info("correctionId=[{}]-[第三方用户新增]-开始-请求参数=[{}]", thirdUserInfoReq.getCorrelationID(), JSON.toJSONString(thirdUserInfoReq));
        try {
            ThirdUserInfo thirdUserInfo = new ThirdUserInfo();
            BeanUtils.copyProperties(thirdUserInfoReq, thirdUserInfo);
            //thirdUserInfoMapper.insertThirdUserSelective(thirdUserInfo);
            thirdUserInfoRes.setCode(FrameworkErrorCodeEnum.SUCCESS.getCode());
            thirdUserInfoRes.setMsg(FrameworkErrorCodeEnum.SUCCESS.getMsg());
            log.info("correlationID=[{}]-[第三方用户新增]-结束-[{}]", thirdUserInfoReq.getCorrelationID(), JSON.toJSONString(thirdUserInfoRes));
        } catch (BusinessException e) {
            log.error("correlationID=[{}]-[第三方用户新增]-业务异常-code=[{}]-msg=[{}]", thirdUserInfoReq.getCorrelationID(),
                    e.getErrorCode(), e.getErrorMessage(), e);
            thirdUserInfoRes.setCode(e.getErrorCode());
            thirdUserInfoRes.setMsg(e.getErrorMessage());
            return thirdUserInfoRes;
        } catch (Exception e) {
            log.error("correlationID=[{}]-[第三方用户新增]-系统异常", thirdUserInfoReq.getCorrelationID(), e);
            thirdUserInfoRes.setCode(FrameworkErrorCodeEnum.SYSTEM_ERR.getCode());
            thirdUserInfoRes.setMsg(FrameworkErrorCodeEnum.SYSTEM_ERR.getMsg());
            return thirdUserInfoRes;
        }
        return thirdUserInfoRes;
    }

    @Override
    //@Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public ThirdUserInfoQueryRes getOrRrgisterWxUserInfo(ThirdUserInfoReq thirdUserInfoReq) {
            ThirdUserInfoQueryRes thirdUserInfoQueryRes = new ThirdUserInfoQueryRes();
        if (thirdUserInfoReq == null || StringUtils.isBlank(thirdUserInfoReq.getOpenId())) {
            log.warn("[微信第三方用户获取或者注册]-请求参数[openId]为空");
            thirdUserInfoQueryRes.setCode(FrameworkErrorCodeEnum.PAPAM_IS_NULL.getCode());
            thirdUserInfoQueryRes.setMsg(FrameworkErrorCodeEnum.PAPAM_IS_NULL.getMsg());
            return thirdUserInfoQueryRes;
        }
        log.info("correctionId=[{}]-[微信第三方用户获取或者注册]-开始-请求参数=[{}]", thirdUserInfoReq.getCorrelationID(), JSON.toJSONString(thirdUserInfoReq));
        try {
            ThirdUserInfo thirdUserInfo = thirdUserInfoMapper.getThirdUserInfoByOpenId(thirdUserInfoReq.getOpenId());
            Integer cityId = null;
            if(thirdUserInfo != null) {
                // 如果unionId为空 需要判断是不是要更新unionId
                if(StringUtils.isBlank(thirdUserInfo.getUnionId()) && StringUtils.isNotBlank(thirdUserInfoReq.getUnionId())) {
                    thirdUserInfo.setUnionId(thirdUserInfoReq.getUnionId());
                    if(redisUtils.hasKey(Constants.WECHAT_OFFICIAL_OPEN_ID_KEY.concat(thirdUserInfo.getUnionId()))) {
                        thirdUserInfo.setOfficialOpenId(redisUtils.get(Constants.WECHAT_OFFICIAL_OPEN_ID_KEY.concat(thirdUserInfo.getUnionId())));
                    }
                    thirdUserInfoMapper.updateByOpenId(thirdUserInfo);
                }

                User user = userMapper.selectByOpenId(thirdUserInfo.getOpenId());
                if (user != null && StringUtils.isBlank(user.getOpenPublic()) && StringUtils.isNotBlank(thirdUserInfoReq.getUnionId())){
                     // 如果unionId为空 需要判断是不是要更新unionId
                    user.setUnionId(thirdUserInfoReq.getUnionId());
                    if(redisUtils.hasKey(Constants.WECHAT_OFFICIAL_OPEN_ID_KEY.concat(thirdUserInfoReq.getUnionId()))) {
                        user.setOpenPublic(redisUtils.get(Constants.WECHAT_OFFICIAL_OPEN_ID_KEY.concat(thirdUserInfoReq.getUnionId())));
                    }
                    log.info("correctionId=[{}]-[微信第三方用户获取或者注册]-查询团团钻老版用户成功-更新公众号openId-[openId]=[{}]-结果=[{}]", thirdUserInfoReq.getCorrelationID(), thirdUserInfoReq.getOpenId(), JSON.toJSONString(user));
                    userMapper.updateById(user);
                }

                if(StringUtils.isNotBlank(thirdUserInfo.getCityId())) {
                    cityId = Integer.valueOf(thirdUserInfo.getCityId());
                } else if(StringUtils.isNotBlank(thirdUserInfoReq.getCityId())) {
                    thirdUserInfo.setCityId(thirdUserInfoReq.getCityId());
                    cityId = Integer.valueOf(thirdUserInfo.getCityId());
                }
                BeanUtils.copyProperties(thirdUserInfo, thirdUserInfoQueryRes);

                if(thirdUserInfo.getUserId() == null) {
                    // 创建用户表信息
                    CustomInfo customInfo = new CustomInfo();
                    customInfo.setStatus(UserStatusEnum.VALID.getCode());
                    customInfo.setCityId(thirdUserInfo.getCityId());
                    customInfo.setGender(thirdUserInfo.getGender());
                    customInfo.setAvatarUrl(thirdUserInfo.getAvatarUrl());
                    customInfo.setNickName(thirdUserInfo.getNickName());
                    customInfo.setStatus(UserStatusEnum.VALID.getCode());
                    customInfo.setPlatType(thirdUserInfoReq.getPlatType());
                    customInfo.setUserType(thirdUserInfo.getUserType());
                    customInfoMapper.insertCustomReturnId(customInfo);
                    log.info("correctionId=[{}]-[微信第三方用户获取或者注册]-custom表新增成功-[openId]=[{}]-userId=[{}]", thirdUserInfoReq.getCorrelationID(), thirdUserInfoReq.getOpenId(), customInfo.getUserId());
                    // 更新userId到第三方用户信息表
                    ThirdUserInfo thirdUserInfoTemp = new ThirdUserInfo();
                    thirdUserInfoTemp.setOpenId(thirdUserInfoReq.getOpenId());
                    thirdUserInfoTemp.setUserId(customInfo.getUserId());
                    thirdUserInfoMapper.updateByOpenId(thirdUserInfoTemp);
                }
            } else {
                // 用户不存在
                log.info("correctionId=[{}]-[微信第三方用户获取或者注册]-用户不存在,需要注册新用户-[openId]=[{}]", thirdUserInfoReq.getCorrelationID(), thirdUserInfoReq.getOpenId());
                // 判断参数中是不是带有用户信息，否则返回用户不存在
                if(StringUtils.isBlank(thirdUserInfoReq.getNickName()) || StringUtils.isBlank(thirdUserInfoReq.getAvatarUrl())) {
                    log.info("correctionId=[{}]-[微信第三方用户获取或者注册]-用户不存在,需要注册新用户-请求中缺少用户信息-[openId]=[{}]", thirdUserInfoReq.getCorrelationID(), thirdUserInfoReq.getOpenId());
                    thirdUserInfoQueryRes.setCode(FrameworkErrorCodeEnum.USER_NOT_EXITS.getCode());
                    thirdUserInfoQueryRes.setMsg(FrameworkErrorCodeEnum.USER_NOT_EXITS.getMsg());
                    return thirdUserInfoQueryRes;
                }
                // 组装用户信息
                thirdUserInfo = new ThirdUserInfo();
                BeanUtils.copyProperties(thirdUserInfoReq, thirdUserInfo);
                if(StringUtils.isNotBlank(thirdUserInfo.getUnionId()) && redisUtils.hasKey(Constants.WECHAT_OFFICIAL_OPEN_ID_KEY.concat(thirdUserInfo.getUnionId()))) {
                    thirdUserInfo.setOfficialOpenId(redisUtils.get(Constants.WECHAT_OFFICIAL_OPEN_ID_KEY.concat(thirdUserInfo.getUnionId())));
                }


                // 城市id转换
                if(StringUtils.isNotBlank(thirdUserInfoReq.getCityId())) {
                    CityQueryReq cityQueryReq = new CityQueryReq();
                    cityQueryReq.setShortName(thirdUserInfoReq.getCityId());
                    List<CityQueryRes> cityList = cityService.listCityByCondition(cityQueryReq);
                    if(cityList != null && !cityList.isEmpty()) {
                        CityQueryRes cityQueryRes = cityList.get(0);
                        cityId = cityQueryRes.getId();
                        thirdUserInfo.setCityId(String.valueOf(cityId));
                    }
                }
                thirdUserInfo.setUserType(StringUtils.isBlank(thirdUserInfoReq.getUserType())?UserTypeEnum.DEFAULT.getValue().toString():thirdUserInfoReq.getUserType());
                // 处理用户头像
                if(StringUtils.isNotBlank(thirdUserInfo.getAvatarUrl())) {
                    URL url = new URL(thirdUserInfo.getAvatarUrl());
                    URLConnection connection = url.openConnection();
                    InputStream is = connection.getInputStream();
                    int length = connection.getContentLength();
                    if (length == 0) {
                        log.warn("correlationID=[{}]-[微信第三方用户获取或者注册]-微信用户头像不存在-openid=[{}]", thirdUserInfoReq.getCorrelationID(), thirdUserInfoReq.getOpenId());
                    } else {
                        //String avatarUrl = fastDFSClient.uploadFile(is, length, "png");
                        UploadRes uploadRes = fileService.uploadOpenFileToOss(is);
                        if(uploadRes != null && StringUtils.equals(FrameworkErrorCodeEnum.SUCCESS.getCode(), uploadRes.getCode())) {
                            thirdUserInfo.setAvatarUrl(uploadRes.getFilePath());
                        }
                    }
                }

                // 兼容原团团钻代码 需要查询ttz.user表是否存在用户，不存在需要添加
                User user = userMapper.selectByOpenId(thirdUserInfo.getOpenId());
                if (user == null){
                    log.info("correctionId=[{}]-[微信第三方用户获取或者注册]-团团钻老版用户不存在,需要新增-[openId]=[{}]", thirdUserInfoReq.getCorrelationID(), thirdUserInfoReq.getOpenId());
                    // 组装用户信息
                    user = new User(null, null, "$2a$10$kOmAT.AywVGBaiajB/VPCOTO4lKbtrLPhywM69.R9mxcvC2O8c2je", thirdUserInfo.getNickName(), thirdUserInfo.getAvatarUrl(), thirdUserInfo.getOpenId(), null, null, null, null, thirdUserInfo.getGender(), null, null, null, null, 1, LocalDateTime.now(), null, null,thirdUserInfo.getUnionId(), thirdUserInfo.getOfficialOpenId());
                    userMapper.insert(user);
                } else {
                    log.info("correctionId=[{}]-[微信第三方用户获取或者注册]-查询团团钻老版用户成功-[openId]=[{}]-结果=[{}]", thirdUserInfoReq.getCorrelationID(), thirdUserInfoReq.getOpenId(), JSON.toJSONString(user));
                    // 如果unionId为空 需要判断是不是要更新unionId
                    if(StringUtils.isBlank(user.getUnionId()) && StringUtils.isNotBlank(thirdUserInfoReq.getUnionId())) {
                        user.setUnionId(thirdUserInfoReq.getUnionId());
                        if(redisUtils.hasKey(Constants.WECHAT_OFFICIAL_OPEN_ID_KEY.concat(thirdUserInfoReq.getUnionId()))) {
                            user.setOpenPublic(redisUtils.get(Constants.WECHAT_OFFICIAL_OPEN_ID_KEY.concat(thirdUserInfoReq.getUnionId())));
                        }
                        userMapper.updateById(user);
                    }
                }
               // redisUtils.set("KEY_USER_ID_" + thirdUserInfoReq.getOpenId(), user.getId().toString());

                // 创建用户表信息
                CustomInfo customInfo = new CustomInfo();
                customInfo.setUserId(user.getId().longValue());
                customInfo.setStatus(UserStatusEnum.VALID.getCode());
                customInfo.setCityId(thirdUserInfo.getCityId());
                customInfo.setGender(thirdUserInfo.getGender());
                customInfo.setNickName(thirdUserInfo.getNickName());
                customInfo.setAvatarUrl(thirdUserInfo.getAvatarUrl());
                customInfo.setStatus(UserStatusEnum.VALID.getCode());
                customInfo.setUserType(thirdUserInfo.getUserType());
                customInfo.setPlatType(thirdUserInfoReq.getPlatType());
                customInfoMapper.insertCustomReturnId(customInfo);
                log.info("correctionId=[{}]-[微信第三方用户获取或者注册]-custom表新增成功-[openId]=[{}]-userId=[{}]", thirdUserInfoReq.getCorrelationID(), thirdUserInfoReq.getOpenId(), customInfo.getUserId());
                thirdUserInfo.setUserId(customInfo.getUserId());
                thirdUserInfo.setSource(thirdUserInfoReq.getSourceType());
                thirdUserInfoMapper.insertThirdUserSelective(thirdUserInfo);
                BeanUtils.copyProperties(thirdUserInfo, thirdUserInfoQueryRes);
            }

            thirdUserInfoQueryRes.setOldUserId(thirdUserInfoQueryRes.getUserId().toString());
            thirdUserInfoQueryRes.setCode(FrameworkErrorCodeEnum.SUCCESS.getCode());
            thirdUserInfoQueryRes.setMsg(FrameworkErrorCodeEnum.SUCCESS.getMsg());
            log.info("correlationID=[{}]-[微信第三方用户获取或者注册]-结束-[{}]", thirdUserInfoReq.getCorrelationID(), JSON.toJSONString(thirdUserInfoQueryRes));
        } catch (BusinessException e) {
            log.error("correlationID=[{}]-[微信第三方用户获取或者注册]-业务异常-code=[{}]-msg=[{}]", thirdUserInfoReq.getCorrelationID(),
                    e.getErrorCode(), e.getErrorMessage(), e);
            thirdUserInfoQueryRes.setCode(e.getErrorCode());
            thirdUserInfoQueryRes.setMsg(e.getErrorMessage());
            return thirdUserInfoQueryRes;
        } catch (Exception e) {
            log.error("correlationID=[{}]-[微信第三方用户获取或者注册]-系统异常", thirdUserInfoReq.getCorrelationID(), e);
            thirdUserInfoQueryRes.setCode(FrameworkErrorCodeEnum.SYSTEM_ERR.getCode());
            thirdUserInfoQueryRes.setMsg(FrameworkErrorCodeEnum.SYSTEM_ERR.getMsg());
            return thirdUserInfoQueryRes;
        }
        return thirdUserInfoQueryRes;
    }

    @Override
    public ThirdUserInfoQueryRes getThirdUserInfo(ThirdUserInfoReq thirdUserInfoReq) {
        ThirdUserInfoQueryRes thirdUserInfoQueryRes = new ThirdUserInfoQueryRes();
        if (thirdUserInfoReq == null || StringUtils.isBlank(thirdUserInfoReq.getOpenId())) {
            log.warn("[查询第三方用户信息]-请求参数[openId]为空");
            thirdUserInfoQueryRes.setCode(FrameworkErrorCodeEnum.PAPAM_IS_NULL.getCode());
            thirdUserInfoQueryRes.setMsg(FrameworkErrorCodeEnum.PAPAM_IS_NULL.getMsg());
            return thirdUserInfoQueryRes;
        }
        log.info("correctionId=[{}]-[查询第三方用户信息]-开始-请求参数=[{}]", thirdUserInfoReq.getCorrelationID(), JSON.toJSONString(thirdUserInfoReq));
        // 兼容老版代码 openId获取的实际是userId，需要转换

        try {
            User user = userMapper.selectById(Integer.valueOf(thirdUserInfoReq.getOpenId()));
            if(user == null) {
                thirdUserInfoQueryRes.setCode(FrameworkErrorCodeEnum.QUERY_RESULT_IS_EMPTY.getCode());
                thirdUserInfoQueryRes.setMsg(FrameworkErrorCodeEnum.QUERY_RESULT_IS_EMPTY.getMsg());
                return thirdUserInfoQueryRes;
            }
            //redisUtils.set("KEY_USER_ID_" + user.getOpenId(), user.getId().toString());
            thirdUserInfoReq.setOpenId(user.getOpenId());
            ThirdUserInfo thirdUserInfo = thirdUserInfoMapper.getThirdUserInfoByOpenId(thirdUserInfoReq.getOpenId());
            if(thirdUserInfo == null) {
                thirdUserInfoQueryRes.setCode(FrameworkErrorCodeEnum.QUERY_RESULT_IS_EMPTY.getCode());
                thirdUserInfoQueryRes.setMsg(FrameworkErrorCodeEnum.QUERY_RESULT_IS_EMPTY.getMsg());
            } else {
                BeanUtils.copyProperties(thirdUserInfo, thirdUserInfoQueryRes);

                // 兼容原团团钻代码 需要查询ttz.user表是否存在用户
                user = userMapper.selectByOpenId(thirdUserInfo.getOpenId());
                thirdUserInfoQueryRes.setOldUserId(user.getId().toString());
                thirdUserInfoQueryRes.setCode(FrameworkErrorCodeEnum.SUCCESS.getCode());
                thirdUserInfoQueryRes.setMsg(FrameworkErrorCodeEnum.SUCCESS.getMsg());
            }
        } catch (BusinessException e) {
            log.error("correlationID=[{}]-[查询第三方用户信息]-业务异常-code=[{}]-msg=[{}]", thirdUserInfoReq.getCorrelationID(),
                    e.getErrorCode(), e.getErrorMessage(), e);
            thirdUserInfoQueryRes.setCode(e.getErrorCode());
            thirdUserInfoQueryRes.setMsg(e.getErrorMessage());
            return thirdUserInfoQueryRes;
        } catch (Exception e) {
            log.error("correlationID=[{}]-[查询第三方用户信息]-系统异常", thirdUserInfoReq.getCorrelationID(), e);
            thirdUserInfoQueryRes.setCode(FrameworkErrorCodeEnum.SYSTEM_ERR.getCode());
            thirdUserInfoQueryRes.setMsg(FrameworkErrorCodeEnum.SYSTEM_ERR.getMsg());
            return thirdUserInfoQueryRes;
        }
        log.info("correlationID=[{}]-[查询第三方用户信息]-结束-[{}]", thirdUserInfoReq.getCorrelationID(), JSON.toJSONString(thirdUserInfoQueryRes));
        return thirdUserInfoQueryRes;
    }
}
